"""
队列 (Queue) - Python实现
先进先出(FIFO)，所有操作O(1)
"""

from collections import deque

class Queue:
    """使用deque实现队列"""
    def __init__(self):
        self._items = deque()
    
    def enqueue(self, item):
        """入队"""
        self._items.append(item)
    
    def dequeue(self):
        """出队"""
        if self.is_empty():
            raise IndexError("队列为空")
        return self._items.popleft()
    
    def front(self):
        """查看队头"""
        if self.is_empty():
            raise IndexError("队列为空")
        return self._items[0]
    
    def is_empty(self):
        return len(self._items) == 0
    
    def size(self):
        return len(self._items)
    
    def __str__(self):
        return f"队头 → {list(self._items)} ← 队尾"

# 应用场景1: 打印队列
def example_print_queue():
    print("\n=== 打印任务队列 ===")
    queue = Queue()
    
    tasks = ["report.pdf", "invoice.pdf", "manual.pdf"]
    for task in tasks:
        queue.enqueue(task)
        print(f"  添加任务: {task}")
    
    print("\n开始打印:")
    while not queue.is_empty():
        task = queue.dequeue()
        print(f"  正在打印: {task}")
    
    print("优势: FIFO保证公平性")

# 应用场景2: BFS
def example_bfs():
    print("\n=== 广度优先搜索 ===")
    print("树结构:")
    print("       1")
    print("      / \\\\")
    print("     2   3")
    print("    / \\\\")
    print("   4   5")
    
    queue = Queue()
    queue.enqueue(1)
    
    print("\nBFS遍历: 1 → 2 → 3 → 4 → 5")
    print("优势: 队列保证层次遍历，找最短路径")

# 应用场景3: 进程调度
def example_process_scheduling():
    print("\n=== CPU进程调度 ===")
    queue = Queue()
    
    processes = ["Browser", "Editor", "Player"]
    for proc in processes:
        queue.enqueue(proc)
    
    print("时间片轮转调度:")
    while not queue.is_empty():
        proc = queue.dequeue()
        print(f"  执行: {proc}")
    
    print("优势: 公平分配CPU时间")

def main():
    print("╔════════════════════════════════════════╗")
    print("║   队列 (Queue) - Python实现             ║")
    print("╚════════════════════════════════════════╝")
    
    queue = Queue()
    queue.enqueue(10)
    queue.enqueue(20)
    queue.enqueue(30)
    print(f"\n{queue}")
    print(f"出队: {queue.dequeue()}")
    print(f"队头: {queue.front()}")
    
    example_print_queue()
    example_bfs()
    example_process_scheduling()
    
    print("\n✅ 优势: 所有操作O(1)，FIFO保证公平")
    print("⚠️ 局限: 只能访问队头和队尾")
    print("💡 应用: 任务调度、BFS、消息队列")
    print("\n🐍 Python特色: collections.deque高效实现")

if __name__ == "__main__":
    main()
